home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 858 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  52 lines

  1. Newsgroups: comp.lang.c
  2. Path: news.ridgecrest.ca.us!owens!mcclung
  3. From: mcclung@owens.ridgecrest.ca.us (Scott McClung)
  4. Subject: Alignment restrictions...
  5. X-Nntp-Posting-Host: owens
  6. Message-ID: <DKxHxG.EK1@ridgecrest.ca.us>
  7. Sender: usenet@ridgecrest.ca.us (Ridgenet Usenet admin)
  8. Organization: Science Applications International Corporation
  9. Date: Tue, 9 Jan 1996 19:24:52 GMT
  10.  
  11. Hi,
  12.  
  13. In architectures that have alignment restrictions on certain types (i.e.
  14. ints aligned on 4 byte boundaries, etc.), does anyone have any clean
  15. way of retrieving values that are not aligned correctly?
  16.  
  17. I was porting some code out that had statements like:
  18.  
  19. short value;  /* 16 bit value */
  20. char *ptr;    /* 32 bit pointer, no alignment restrictions */
  21.  
  22. value = *(short *)ptr;
  23.  
  24. It worked on, say, Intel x86, or on values of ptr that happened to be
  25. aligned (auto variables, in this case), but is not a general solution
  26. on SPARC or other RISC architectures (MIPS and PA-RISC have similar
  27. restrictions, if I recall.)  The pointer in question happened to be
  28. into an mmap()'ed image file, so the alignment is not guaranteed.  Bus
  29. errors.
  30.  
  31. I replaced it with:
  32.  
  33. value = *ptr << 8 | *(ptr + 1);
  34.  
  35. Which works.  I'd just like to find out how this is generally dealt
  36. with in code...  Actually, a magic compiler switch would be nice. :-)
  37. (I'm working with gcc 2.7.2, BTW.)  I'll probably replace the
  38. statement above with some inline function that checks the alignment of
  39. ptr, and acts appropriately.  I guess I'm just looking for your
  40. collective wisdom on this topic.
  41.  
  42. Any suggestion of a better group to post this in will also be helpful.
  43.  
  44. Thanks...
  45.  
  46. -- 
  47. /* Scott McClung                   Opinions expressed here are mine.
  48.  * UNIX Software Engineer/UNIX System Admin
  49.  * mcclung@imt.saic.com
  50.  * mcclung@ridgecrest.ca.us
  51.  */
  52.